package com.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时取出ApplicaitonContext
 * 该文件与App.java同包或其子包下，正常使用，
 * 其它位置需要在App.java指定扫描包@ComponentScan({"com.inspur","com.igap.data"})
 * 或配置导入 @Import(value={SpringUtil.class})
 */
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);

    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋对象的类
     */

    public static <T> T getBean(Class<T> class1) {
        assertContextInjected();
        return applicationContext.getBean(class1);
    }
    public static <T> T getBean(String className) {
        assertContextInjected();
        return (T)applicationContext.getBean(className);
    }
    public static <T> T getBean(String beanName,Class<T> class1) {
        assertContextInjected();
        return applicationContext.getBean(beanName,class1);
    }

    /**
     * 清除SpringContextHolder中的ApplicationContext为Null.
     */
    public static void clearHolder() {
        logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
        applicationContext = null;
    }

    /**
     * 实现ApplicationContextAware接口, 注入Context到静态变量中.
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
        logger.debug("注入ApplicationContext到SpringContextHolder:{}", applicationContext);

        if (SpringContextHolder.applicationContext != null) {
            logger.warn("SpringContextHolder中的ApplicationContext被覆原有ApplicationContex"
                    + SpringContextHolder.applicationContext);
        }

        SpringContextHolder.applicationContext = applicationContext; //NOSONAR
    }

    /**
     * 实现DisposableBean接口, 在Context关闭时清理静态变
     */

    public void destroy() throws Exception {
        SpringContextHolder.clearHolder();
    }

    /**
     * ApplicationContext不为
     */
    private static void assertContextInjected() {
    	if(applicationContext == null){
    		logger.error("applicaitonContext请在applicationContext.xml中定义SpringContextHolder.");
    		throw new RuntimeException("applicaitonContext请在applicationContext.xml中定义SpringContextHolder.");
    	}
    }
}
